import os
import csv

__all__ = ['ToolkitFetcher']
from ..fetcher import *
class Toolkit(Fetcher):

    #!!!todo: make all these options to be passed from script command-line options (through fetchers' base factory)
    def read(self, fields, entity, *, filedir, filetpl = "dbo_%s.csv", delimiter = ';', quotechar = '~', encoding = 'windows-1251'):
        return csv.DictReader(
                open(os.path.join(filedir, filetpl % entity),
                newline="", encoding=encoding, ),
                delimiter=delimiter, quotechar=quotechar, )

    def cast(self, caster, value):
        if value in (None, "", "null", "Null", "NULL"): return None
        if caster == float: return caster(value.replace("\xA0", "").replace(",", "."))
        if caster == int  : return caster(value.replace("\xA0", ""))
        if caster == bool : return caster(value in ("True", "true"))#@TODO: raise if value is not in true, nor in false list
        if caster == str  : return caster(value)
        raise TypeError("Fetcher does not support casters of type "+repr(type(caster))+".")
